package cn.com.ayqu.module.erp.controller.admin.activityuser;

import cn.com.ayqu.framework.common.util.collection.MapUtils;
import cn.com.ayqu.module.erp.dal.dataobject.activity.ActivityDO;
import cn.com.ayqu.module.erp.dal.dataobject.sale.ErpCustomerCarNumberDO;
import cn.com.ayqu.module.erp.dal.dataobject.sale.ErpCustomerDO;
import cn.com.ayqu.module.erp.dal.dataobject.sale.ErpSaleOrderDO;
import cn.com.ayqu.module.erp.service.activity.ActivityService;
import cn.com.ayqu.module.erp.service.sale.ErpCustomerService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;

import cn.com.ayqu.framework.common.pojo.PageParam;
import cn.com.ayqu.framework.common.pojo.PageResult;
import cn.com.ayqu.framework.common.pojo.CommonResult;
import cn.com.ayqu.framework.common.util.object.BeanUtils;
import static cn.com.ayqu.framework.common.pojo.CommonResult.success;

import cn.com.ayqu.framework.excel.core.util.ExcelUtils;

import cn.com.ayqu.framework.apilog.core.annotation.ApiAccessLog;
import static cn.com.ayqu.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.com.ayqu.framework.common.util.collection.CollectionUtils.convertSet;

import cn.com.ayqu.module.erp.controller.admin.activityuser.vo.*;
import cn.com.ayqu.module.erp.dal.dataobject.activityuser.ActivityUserDO;
import cn.com.ayqu.module.erp.service.activityuser.ActivityUserService;

@Tag(name = "管理后台 - 用户参与活动")
@RestController
@RequestMapping("/erp/activity-user")
@Validated
public class ActivityUserController {

    @Resource
    private ActivityUserService activityUserService;

    @Resource
    private ActivityService activityService;

    @Resource
    private ErpCustomerService customerService;

    @PostMapping("/create")
    @Operation(summary = "创建用户参与活动")
    @PreAuthorize("@ss.hasPermission('erp:activity-user:create')")
    public CommonResult<Long> createActivityUser(@Valid @RequestBody ActivityUserSaveReqVO createReqVO) {
        return success(activityUserService.createActivityUser(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户参与活动")
    @PreAuthorize("@ss.hasPermission('erp:activity-user:update')")
    public CommonResult<Boolean> updateActivityUser(@Valid @RequestBody ActivityUserSaveReqVO updateReqVO) {
        activityUserService.updateActivityUser(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户参与活动")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:activity-user:delete')")
    public CommonResult<Boolean> deleteActivityUser(@RequestParam("id") Long id) {
        activityUserService.deleteActivityUser(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户参与活动")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:activity-user:query')")
    public CommonResult<PageResult<ActivityUserRespVO>> getActivityUser(@Valid ActivityUserDetailPageReqVO pageReqVO) {
        PageResult<ActivityUserDO> list = activityUserService.getActivityUser(pageReqVO);
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<ActivityUserRespVO> activityUserRespVOPageResult = buildActivityUserVOPageResult(pageReqVO.getActivityId(), list);

        BigDecimal total = BigDecimal.ZERO;
        for (ActivityUserRespVO activityUserRespVO : activityUserRespVOPageResult.getList()) {
            if (activityUserRespVO.getCeilMoney() == null) {
                activityUserRespVO.setCeilMoney(BigDecimal.ZERO);
            }

            if (activityUserRespVO.getActivityMoney().compareTo(BigDecimal.ZERO) > 0) {
                total = total.add(activityUserRespVO.getActivityMoney().subtract(activityUserRespVO.getCeilMoney()));
            }
            if (activityUserRespVO.getType() == 1) {
                activityUserRespVO.setCeilMoney(total.subtract(activityUserRespVO.getUseMoney()));
            } else {
                activityUserRespVO.setCeilMoney(total.add(activityUserRespVO.getUseMoney()));
            }

            total = activityUserRespVO.getCeilMoney();
        }

        return success(activityUserRespVOPageResult);
    }

    @GetMapping("/get-join-info")
    @PreAuthorize("@ss.hasPermission('erp:activity-user:query')")
    public CommonResult<ActivityUserDO> getJoinInfo(@RequestParam("id") Long id) {
        ActivityUserDO activityUser = activityUserService.getActivityUserJoinInfo(id);
        return success(activityUser);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户参与活动分页")
    @PreAuthorize("@ss.hasPermission('erp:activity-user:query')")
    public CommonResult<PageResult<ActivityUserRespVO>> getActivityUserPage(@Valid ActivityUserPageReqVO pageReqVO) {
        PageResult<ActivityUserDO> pageResult = activityUserService.getActivityUserPage(pageReqVO);

        return success(buildActivityUserVOPageResult(pageReqVO.getActivityId(), pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户参与活动 Excel")
    @PreAuthorize("@ss.hasPermission('erp:activity-user:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportActivityUserExcel(@Valid ActivityUserPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ActivityUserRespVO> list = buildActivityUserVOPageResult(
                pageReqVO.getActivityId(), activityUserService.getActivityUserPage(pageReqVO)
        ).getList();
        // 导出 Excel
        ExcelUtils.write(response, "用户参与活动.xls", "数据", ActivityUserRespVO.class,
                        BeanUtils.toBean(list, ActivityUserRespVO.class));
    }

    private PageResult<ActivityUserRespVO> buildActivityUserVOPageResult(Long activityId, PageResult<ActivityUserDO> pageResult) {
        if (pageResult.getList().isEmpty()) {
            return PageResult.empty(pageResult.getTotal());
        }
        ActivityDO activity = activityService.getActivity(activityId);

        Map<Long, ErpCustomerDO> customerMap = customerService.getCustomerMap(
                convertSet(pageResult.getList(), ActivityUserDO::getUserId));

        Map<Long, List<ErpCustomerCarNumberDO>> customerAllCarNumberMap = customerService.getCustomerAllCarNumberMap(
                convertSet(pageResult.getList(), ActivityUserDO::getUserId)
        );

        return BeanUtils.toBean(pageResult, ActivityUserRespVO.class, activityUserRespVO -> {
            activityUserRespVO.setActivityName(activity.getActivityName())
                    .setActivityDesc(activity.getActivityDesc());

            MapUtils.findAndThen(customerMap, activityUserRespVO.getUserId(), customer -> activityUserRespVO.setUsername(customer.getName()));

            MapUtils.findAndThen(customerAllCarNumberMap, activityUserRespVO.getUserId(), carNumber ->
                    activityUserRespVO.setCarNumber(carNumber.stream().map(ErpCustomerCarNumberDO::getCarNumber).toList())
            );
        });
    }

}